package com.blb.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyServer {

    public static final int PORT = 8888;

    public void start(){
        System.out.println("服务器启动了。。。。");
        //创建服务器端Socket
        try(ServerSocket serverSocket = new ServerSocket(PORT)){
            for(;;){
                //接收客户端连接，没有客户端连接，会产生阻塞，直到有连接过来
                Socket socket = serverSocket.accept();
                System.out.println(socket.getInetAddress() +"连上来了！");
                //获得客户端的输入流，读取客户端消息
                try(DataInputStream in = new DataInputStream(socket.getInputStream());
                    DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
                    String msg = in.readUTF();
                    System.out.println(socket.getInetAddress() + "说：" + msg);
                    //发送消息给客户端
                    out.writeUTF("你好啊，客户端，我是服务器！");
                    out.flush();
                }catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new MyServer().start();
    }
}
